'use strict';

import { ServiceBase, Exceptions } from '../kalend';
import { gifthistoryModel } from '../model/gifthistory';
import { customer_accountService } from './customer_account';
import { ObjectId } from 'bson';
var moment = require("moment");

class GifthistoryService extends ServiceBase {
    constructor() {
        super(gifthistoryModel)
    }
    async query(params: any) {
        const offset = params.page || 1;
        const limit = params.limit || 15;

        let data = await this.queryPagination(offset, limit, {
            select: 'nickname updateTime remarks phone status'
        });
        data.rows = data.rows.map((item) => {
            item.getTime = moment(item.updateTime).format("YYYY-MM-DD HH:mm:ss");
            return item;
        });
        return data.rows;
    }
    async upstate(uid: any) {
        let data = await this.querySingle({ userid: uid });
        if (data) {
            this.update(data._id, { status: '已领取' });
        }
    }

    async sendgift(doc: any) {
        let uid = doc.uid;
        let sendphone = doc.sendphone;
        let senduser = await customer_accountService.querySingle({ isender: true, phone: sendphone }, { select: 'phone isender' });
        if (senduser) {
            let userdata = await customer_accountService.queryById(uid);
            if (userdata && userdata.isgetgift) {
                throw Exceptions.known('礼品已领取');
            }
            let data = await this.querySingle({ userid:new ObjectId(uid) });
            if (data) {
                this.update(data._id, { status: '已领取', sendid: senduser._id, sendphone: sendphone });
                customer_accountService.update(uid, { $set: { isgetgift: true } });
                return {
                    msg: '礼品发放成功'
                };
            } else {
                throw Exceptions.known('当前用户无领取礼品权限');
            }
        } else {
            throw Exceptions.known('礼品发放失败，您不是礼品发放人，请联系管理员');
        }
    }
}

export const gifthistoryService = new GifthistoryService();